
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'dart:convert';
import 'package:maintenancerecord/pages/common/diglog_page.dart';
import 'package:maintenancerecord/pages/records/DessertDataSource.dart';
import 'package:maintenancerecord/pages/records/record_comment.dart';
import 'package:maintenancerecord/pages/records/record_datatable.dart';
import 'package:maintenancerecord/pages/records/record_view_comment.dart';
import 'package:maintenancerecord/pages/service/repair_service.dart';

class RecordIndexPage extends StatefulWidget {
  final String content;

  const RecordIndexPage({Key? key, required this.content}) : super(key: key);

  @override
  State<RecordIndexPage> createState() => _RecordIndexPageState();
}

class _RecordIndexPageState extends State<RecordIndexPage> {

  TextEditingController datecontroller=TextEditingController();
  TextEditingController namecontroller=TextEditingController();


  int pageSize = 10;
  int _nowPageNum = 1;
  int _pageCountNums = 4;
  String userName = "", date = "";


  List<DataRow> desserts = [];

  int dataCountNums = 0;

  @override
  void initState() {
    super.initState();
    loadPageData();
  }


  @override
  Widget build(BuildContext context) {
    //边框样式
    OutlineInputBorder _outlineInputBorder = OutlineInputBorder(
      gapPadding: 0,
      borderSide: BorderSide.none,
    );

    return SizedBox(
      child: Column(
        children: [

          // 标题
          Container(
              height: 43,
              color: Colors.white70,
              child: Container(
                child: Center(child: Text("记录查询", style: TextStyle(fontSize: 34, fontWeight: FontWeight.w500, fontFamily: 'YouSheBiaoTiHei' ),),),
              )
          ),

          // 搜索栏
          Container(
            height: 45,
            child: Row(
              children: [
                Wrap(
                  alignment: WrapAlignment.start,
                  direction: Axis.horizontal,
                  runSpacing: 2,
                  spacing: 2,
                  children: [


                    Container(
                      padding: EdgeInsets.all(9),
                      width: 35,
                      height: 35,
                      child: Icon(Icons.psychology, color: Colors.grey,),
                    ),
                    Container(
                      margin: EdgeInsets.all(5),
                      width: 180,
                      height: 35,
                      child: TextField(
                        autofocus: true,
                        scrollPadding: EdgeInsets.all(4.0),
                        controller: namecontroller,
                        decoration: InputDecoration(
                          fillColor: Colors.grey[50],//背景颜色，必须结合filled: true,才有效
                          filled: true,//重点，必须设置为true，fillColor才有效
                          isCollapsed: true,//重点，相当于高度包裹的意思，必须设置为true，不然有默认奇妙的最小高度
                          contentPadding: EdgeInsets.symmetric(horizontal: 8, vertical: 10),//内容内边距，影响高度
                          border: OutlineInputBorder(),
                          hintStyle: TextStyle(fontSize: 12, ),
                          hintText: "请输入教职员/学生",
                        ),
                        onChanged: (v) {
                          //print(v);
                        },
                      ),
                    ),


                    Container(
                      padding: EdgeInsets.all(9),
                      width: 35,
                      height: 35,
                      child: Icon(Icons.date_range, color: Colors.grey,),
                    ),
                    Container(
                      margin: EdgeInsets.all(5),
                      width: 180,
                      height: 35,
                      child: CupertinoTextField(
                        controller: datecontroller,
                        padding: EdgeInsets.all(4),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(4.0)),
                          border: Border(
                            top: BorderSide(width: 2.0, color: Colors.grey),
                            bottom: BorderSide(width: 2.0, color: Colors.grey),
                            left: BorderSide(width: 2.0, color: Colors.grey),
                            right: BorderSide(width: 2.0, color: Colors.grey),
                          ),
                        ),
                        style: TextStyle(color: Colors.blue),
                        suffix: IconButton(
                          padding: EdgeInsets.all(4),
                          icon: Icon(CupertinoIcons.clear),
                          onPressed: () {
                            datecontroller.clear();
                          },
                        ),
                        suffixMode: OverlayVisibilityMode.editing,
                        cursorColor: Colors.purple,
                        cursorWidth: 2,
                        cursorRadius: Radius.circular(2),
                        readOnly: true,
                        placeholder: '请输选择日期',
                        onTap: showDateDialog,
                      ),

                    ),

                    Container(
                      margin: EdgeInsets.all(2),
                      width: 105,
                      height: 38,
                      // color: Colors.grey.withAlpha(33),
                      child: ElevatedButton.icon(
                        icon: Icon(Icons.search),
                        label: Text("查询"),
                        onPressed: () {
                          setState(() {
                            userName = namecontroller.value.text;
                            date = datecontroller.value.text;
                          });
                          loadPageData();
                        },
                      ),
                    ),


                  ],
                ),

              ],
            ),
          ),

          // 数据列表
          Container(
            // color: Colors.white30,
            height: 610,
            child: RecordDataTable(rows: desserts,),
          ),

          // 翻页控件
          Container(
            height: 40,
            // color: Colors.red,
            child: Container(
              child: Row(
                children: [
                  Padding(
                    child: Text(""),
                    padding: EdgeInsets.only(left: 25, right: 20)
                  ),
                  Expanded(
                    child: Text("")
                  ),
                  Padding(
                    child: Row(
                      children: [
                        Text("第${_nowPageNum}页/共${_pageCountNums}页", style: TextStyle(fontSize: 12, color: Colors.black54),),
                        Visibility(
                          child: IconButton(
                            // onPressed: null,
                            onPressed: PageUp,
                            icon: Icon(Icons.keyboard_arrow_left, color: Colors.black54,)
                          ),
                          visible:_nowPageNum == 1 ? false : true,
                        ),
                        Visibility(
                          child: IconButton(
                            // onPressed: null,
                            onPressed: PageDown,
                            icon: Icon(Icons.keyboard_arrow_right, color: Colors.black54,)
                          ),
                          visible:_nowPageNum == _pageCountNums ? false : true,
                        ),


                      ],
                    ),
                    padding: EdgeInsets.only(right: 25),
                  ),


                ],
              ),
            )
          ),


        ],
      ),
    );

  }

  showDateDialog() async {
    DateTime? result = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2020),
        lastDate: DateTime(2025),
        initialEntryMode: DatePickerEntryMode.calendarOnly,
        helpText: "选择日期",
        cancelText: "取消",
        confirmText: "确定"
    );
    if(null != result) {
      int? _m = result?.month;
      int? _d = result?.day;
      String _day = "${result?.year}";
      if(null != _m && _m < 10) {
        _day += "-0${_m}";
      } else {
        _day += "-${_m}";
      }
      if(null != _d && _d < 10) {
        _day += "-0${_d}";
      } else {
        _day += "-${_d}";
      }

      setState(() {
        datecontroller.value = TextEditingValue(text: _day);
      });
    }
  }


  void PageUp() {
    setState(() {
      _nowPageNum = _nowPageNum-1;
    });
    loadPageData();
  }

  void PageDown() {
    setState(() {
      _nowPageNum = _nowPageNum+1;
    });
    loadPageData();
  }

  void loadPageData () {
    Future _response = RepairService.page(context, _nowPageNum.toString(), userName, date);
    _response.then((response) {
      if(response.statusCode == 200) {
        Map res = jsonDecode(utf8.decode(response.bodyBytes)) as Map;
        if(res["code"] == 200) {
          Map _pageObj = res["data"] as Map;
          List listData = _pageObj['records'];
          List<DataRow> _rows = convertPageData(listData);
          setState(() {
            desserts = _rows;
            _nowPageNum = _pageObj['current'];
            _pageCountNums = _pageObj['pages'];
          });
        } else {
          DialogTools.showAlertDialog(context, "提示", res["info"]);
        }
      }
    });


  }

  List<DataRow> convertPageData(List rows) {
    List<DataRow> _nrows = [];
    for(int i = 0; i < rows.length; i++) {
      Map info = rows[i];
      List<String> _optState = ["已  完  成", "处  理  中", "暂未处理" ];
      List<String> _optType = ["硬件", "软件", "网络" , "其他" ];
      _nrows.add(DataRow(
          cells: <DataCell>[
            DataCell(Text(info["reportUserName"])),
            DataCell(Text(_optType[info["repairType"]])),
            DataCell(
                Row(children: [
                  Text(_optState[info["processState"]]), info["processState"] != 0 ? Icon(Icons.edit, color: Colors.deepOrangeAccent,) : Icon(Icons.check, color: Colors.lightGreenAccent,),
                ],),
                onTap: info["processState"] != 0 ? () {continueRepair(info);} : null
            ),
            DataCell(Text((info["commentUserName"]) == null?'':info["commentUserName"])),

            DataCell(
                Row(children: [
                  Text(info["lastUpdateTime"]), Icon(Icons.history, color: Colors.lightBlue,),
                ],),
                onTap: () {viewRepairComment(info["recordId"]);}
            ),
            // DataCell(Text(info["lastUpdateTime"])),
          ]
      ));
    }
    return _nrows;
  }

  void continueRepair(Map info) {
    showDialog(context: context, builder: (ctx) => RecordComment(info: info) ).then((value)
    {
      print("我刷新了");
      setState(() {
        _nowPageNum = 1;
      });
      loadPageData();

    });
  }

  void viewRepairComment(int recordId) {
    showDialog(context: context, builder: (ctx) => RecordViewComment(recordId: recordId)).then((value)
    {
      print("我刷新了");
      // setState(() {
      //   _nowPageNum = 1;
      // });
      // loadPageData();

    });
  }

}

